#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys

try:
    import ConfigParser as cfgParser
except:
    import configparser as cfgParser

from mie.cmdsplit import cmdSplit
from mie.bprint import varfmt


def getInfo(path):
    try:
        cp = cfgParser.ConfigParser()
        cp.read(path)
        item = cp.get("include", "files")
        cfgDir = os.path.dirname(item)
        _, cfgExt = os.path.splitext(item)

        if not os.path.isabs(cfgDir):
            cfgDir = os.path.join(os.path.dirname(path), cfgDir)

        return cfgDir, cfgExt
    except:
        return None, None


def guessInfo():
    pa = "/etc/supervisor/supervisord.conf"
    pb = "/etc/supervisord.conf"

    cfgDir, cfgExt = getInfo(pa)
    if not cfgDir:
        cfgDir, cfgExt = getInfo(pb)

    return cfgDir, cfgExt


def help():
    print("supadd: Add command supervisor")
    print("Usage: supadd -once --name --user --dir -- commands ...")
    print("      -v : verbose")
    print("   -once : oneshort")
    print("  --name : progName")
    print("  --user : runasUser")
    print("   --dir : workDir")
    sys.exit(0)


def getCmdPath(cmdName):
    def which(name):
        pathLis = os.environ.get("PATH").split(":")
        for path in pathLis:
            fullPath = os.path.join(path, cmdName)
            if os.path.exists(fullPath):
                return fullPath
        return None

    if os.path.dirname(cmdName) == "":
        # cmd args ...
        # the command is in search path
        return which(cmdName)
    else:
        return os.path.realpath(cmdName)


def main():
    if "--help" in sys.argv:
        help()

    cmd = cmdSplit(sys.argv)
    verbose = cmd.opts_nth("v", 0)
    if verbose:
        print(varfmt(cmd))

    progName = cmd.opts_nth("name", 0)
    userName = cmd.opts_nth("user", 0)
    workDir = cmd.opts_nth("dir", 0, os.getcwd())

    # Get real command
    cmdPath = getCmdPath(cmd.args[0])
    cmd.args[0] = cmdPath
    command = " ".join(cmd.args)

    if not progName or not command:
        help()

    cfgDir, cfgExt = guessInfo()

    iniLines = []
    iniLines.append("[program:%s]" % progName)
    iniLines.append("command=%s" % command)

    once = cmd.opts_nth("once", 0)
    iniLines.append("autorestart=%s" % ("false" if once else "true"))
    iniLines.append("directory=%s" % workDir)

    if userName:
        iniLines.append("user=%s" % userName)

    path = os.path.join(cfgDir, progName + cfgExt)
    if verbose:
        print(">>> Writing %s" % path)
        print("-" * 30)
        print("\r\n".join(iniLines))
        print("-" * 30)

    try:
        open(path, "wt").write("\r\n".join(iniLines))
    except:
        print("Write %s failed" % path)

    try:
        os.system("supervisorctl update")
    except:
        print("Error: supervisorctl update")


if __name__ == "__main__":
    try:
        main()
    except:
        help()
